package com.victor.controller.app;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.LoginQuestion;
import com.victor.entity.User;
import com.victor.entity.UserBankcard;
import com.victor.service.UserService;
import com.victor.utils.ClassFilter;
import com.victor.utils.CodeUtil;
import com.victor.utils.EmailUtil;
import com.victor.utils.Msg;
import com.victor.utils.wxlogin.SNSUserInfo;
import com.victor.utils.wxlogin.WxController;

@RestController
@RequestMapping("/app")
public class UserController {
	private static Logger log = LoggerFactory.getLogger(UserController.class);

	// 定义定时器
	private Timer timer = new Timer();

	// 定义验证码list
	private static List<Map<String, Object>> codelist = new ArrayList<Map<String, Object>>();
	@Autowired
	private UserService userService;

	/**
	 * 微信登陆
	 * 
	 * @param code
	 * @return
	 */
	@PostMapping("/wechartLogin")
	public Msg wechartLogin(String code) {
		SimpleDateFormat sdf = new SimpleDateFormat();
		if (null == code || code.isEmpty()) {
			return Msg.fail();
		}
		SNSUserInfo snsUserInfo = null;
		try {
			snsUserInfo = WxController.weixinLogin(code);
			User user = userService.findByOpenid(snsUserInfo.getOpenId());
			if (user == null) {
				user = new User();
				user.setOpenid(snsUserInfo.getOpenId());
				user.setNickname(snsUserInfo.getNickname());
				user.setHeadphoto(snsUserInfo.getHeadImgUrl());
				user.setZhucedata(sdf.format(new Date()));
				userService.insert(user);
			}
			return Msg.success().add("user", user);

		} catch (Exception e) {
			log.error("--UserController.wechartLogin->:{}", e);
			return Msg.fail();
		}

	}

	/**
	 * qq登陆
	 * @param qqopenid
	 * @return
	 */
	@PostMapping("/qqLogin")
	public Msg qqLogin(String qqopenid) {
		if (null == qqopenid) {
			return Msg.fail();
		}
		User user = userService.qq(qqopenid);
		return Msg.success().add("user", user);
	}

	/**
	 * 账号登陆
	 * @param account
	 * @param password
	 * @return
	 */
	@PostMapping("/accountlogin")
	public Msg mailLogin(String account, String password) {
		if (null == account || account.isEmpty() || null == password || password.isEmpty()) {
			return Msg.fail("参数错误");
		}
		User user = userService.mailLogin(account, password);
		if (user != null) {
			return Msg.success().add("user", user);
		}
		return Msg.fail("登陆失败");
	}

	/**
	 * 生成验证码 有效期2分钟
	 * 
	 * @param mobile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/buildcode")
	public Msg buildcode(String mobile) throws Exception {
		if (mobile == null || mobile.equals("")) {
			return Msg.fail("手机号为空");
		}
		// 关闭timer
		timer.cancel();
		// new一个Timer
		timer = new Timer();

		Map<String, Object> m2 = new HashMap<String, Object>();
		// 生成验证码(6位随机的验证码)
		String random = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
		System.out.println(mobile + " ~~~" + random);
		// 第三方发送短息 
		// AliMobileCode.getMessage(mobile, random);
		// 删除该手机号在codelist中其他的验证信息
		CodeUtil.clearothermap(codelist, mobile);
		// 将随机验证码放入到全局map中
		m2.put("random", random);
		m2.put("mobile", mobile);
		codelist.add(m2);
		m2 = new HashMap<String, Object>();

		// 设置定时器2分钟清空mmmlist
		timer.schedule(new TimerTask() {
			public void run() {
				codelist.clear();
			}
		}, 2 * 60 * 1000);// 设定指定的时间time,此处为2*60*1000毫秒
		return Msg.success().add("code", random);
	}

	/**
	 * 手机号验证登录（或者忘记密码验证）
	 * 
	 * @param mobile
	 * @param code
	 * @return
	 */
	@RequestMapping("/phonelogin")
	public Msg submitJionMessage(String mobile, String code) {
		if (mobile == null || code == null) {
			return Msg.fail("参数错误");
		}
		// 获取验证码
		String random = CodeUtil.getmapvalue(codelist, mobile);
		// 判断验证码是否正确
		if (code.equals(random)) {
			// 验证码用后失效
			Map<String, String> map = new HashMap<String, String>();
			map.put("mobile", mobile);
			map.put("random", random);
			codelist.remove(map);
			User user = userService.selByPhone(mobile);
			if (user == null) {
				return Msg.fail("该手机号不存在");
			} else {
				return Msg.success().add("user", user);
			}
		} else {
			return Msg.fail("验证码错误");
		}
	}

	/**
	 * 注册时 验证账号
	 * 
	 * @param account
	 * @return
	 */
	@RequestMapping("/validation")
	public Msg validateAccount(String account) {
		if (account == null || account.isEmpty()) {
			return Msg.fail("入参失败");
		}
		User selByAccount = userService.selByAccount(account);
		if (selByAccount != null) {
			return Msg.fail("该账号已经被使用");
		}
		return Msg.success();
	}

	/**
	 * 注册账号
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/registaccount")
	public Msg regist(User user, String code) {
		String mobile = user.getPhone();
		if (mobile == null || code == null) {
			return Msg.fail("参数错误");
		}
		// 获取验证码
		String random = CodeUtil.getmapvalue(codelist, mobile);
		// 判断验证码是否正确
		if (code.equals(random)) {
			// 验证码用后失效
			Map<String, String> map = new HashMap<String, String>();
			map.put("mobile", mobile);
			map.put("random", random);
			codelist.remove(map);
			String[] str = { "phone", "mailbox", "account", "question1", "question2", "question3", "answer1", "answer2",
					"answer3" };
			boolean empty = ClassFilter.somePropertyIsEmpty(user, str);
			if (empty == true) {
				return Msg.fail("用户入参失败");
			}
			boolean b = userService.insert(user);
			return Msg.judge(b);
		} else {
			return Msg.fail("验证码错误");
		}

	}

	/**
	 * 忘记密码返回电话和邮箱
	 * 
	 * @param account
	 * @return
	 */
	public Msg forgetPassword(String account) {
		if (account == null || account.isEmpty()) {
			return Msg.fail("入参错误");
		}
		User user = userService.mailLogin(account, null);
		return Msg.success().add("user", user);
	}

	/**
	 * 忘记密码-设置密码(手机号和邮箱)
	 * 
	 * @param user
	 * @return
	 */
	public Msg setPassword(User user) {
		if (user.getId() == null || user.getPassword() == null || user.getPassword().isEmpty()) {
			return Msg.fail("入参错误");
		}
		boolean b = userService.updateUser(user);
		return Msg.judge(b);
	}

	/**
	 * 发送邮箱验证码
	 * 
	 * @param mail
	 * @return
	 */
	public Msg sendMail(String mail) {
		if (mail == null || mail.isEmpty()) {
			return Msg.fail("入参失败");
		}
		timer.cancel();
		timer = new Timer();
		Map<String, Object> m2 = new HashMap<String, Object>();
		// 生成验证码(6位随机的验证码)
		String random = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
		//TODO	
		EmailUtil.sendEmailCode(mail, random);
		CodeUtil.clearMailothermap(codelist, mail);
		// 将随机验证码放入到全局map中
		m2.put("random", random);
		m2.put("mail", mail);
		codelist.add(m2);
		m2 = new HashMap<String, Object>();

		// 设置定时器2分钟清空mmmlist
		timer.schedule(new TimerTask() {
			public void run() {
				codelist.clear();
			}
		}, 2 * 60 * 1000);// 设定指定的时间time,此处为2*60*1000毫秒
		return Msg.success().add("code", random);
	}

	/**
	 * 邮箱验证
	 * 
	 * @param mail
	 * @param code
	 * @return
	 */
	public Msg mailRandom(String mail, String code) {
		if (code == null || code.isEmpty() || mail == null || mail.isEmpty()) {
			return Msg.fail("入参错误");
		}
		String random = CodeUtil.getMailmapvalue(codelist, mail);
		if (code.equals(random)) {
			// 验证码用后失效
			Map<String, String> map = new HashMap<String, String>();
			map.put("mail", mail);
			map.put("random", random);
			codelist.remove(map);
			User selByMail = userService.selByMail(mail);
			if (selByMail == null) {
				return Msg.fail("没有这个邮箱用户");
			}
			return Msg.success().add("user", selByMail);
		} else {
			return Msg.fail("验证码错误");
		}
	}
	/**
	 * 修改密码 验证申诉
	 * @param user
	 * @param bankcard
	 * @return
	 */
	public Msg complaintPassword(User user, String bankcard) {
		String[] str = { "id", "idcard", "password" };
		boolean empty = ClassFilter.somePropertyIsEmpty(user, str);
		if (empty == true) {
			return Msg.fail("入参错误");
		}
		User selById = userService.selById(user.getId());
		if (selById == null) {
			return Msg.fail("没有这个用户");
		}
		if (user.getIdcard().equals(selById.getIdcard())) {
			List<UserBankcard> banklist = userService.selBankCard(user.getId());
			if (banklist == null) {
				return Msg.fail("没有银行卡");
			}
			for (UserBankcard userbankcard:banklist) {
				if (bankcard.equals(userbankcard.getBankcardnum())) {
						if (user.getPhone() != null) {
							if (user.getMailbox() != null) {
								if (user.getPhone().equals(selById.getPhone())&& user.getMailbox().equals(selById.getMailbox())) {
									boolean b = userService.updateUser(user);
									return Msg.judge(b);
								}else {
									return Msg.fail("手机或者邮箱不对");
								}
							}else {
								if (user.getPhone().equals(selById.getPhone())) {
									boolean b = userService.updateUser(user);
									return Msg.judge(b);
								}else {
									return Msg.fail("手机不对");
								}
							}
						}else {
							if (user.getMailbox() != null) {
								if (user.getMailbox().equals(selById.getMailbox())) {
									boolean b = userService.updateUser(user);
									return Msg.judge(b);
								}else {
									return Msg.fail("邮箱错误");
								}
							}else {
								return Msg.fail("邮箱和手机都空");
							}
						}
				}else {
					return Msg.fail("银行卡不存在");
				}
			}
			
		}else {
			return Msg.fail("身份证错误");
		}
		return Msg.success();
	}
	/**
	 * 遇到的问题
	 * @return
	 */
	@RequestMapping("/loginquestion00")
	public Msg getQuestion() {
		List<LoginQuestion> list = userService.selLoginQuestion();
		return Msg.success().add("question", list);
	}
}
